/*
* PROJECT: Happy New Year
* VERSION: 1.0
* AUTHOR: Mattias Thell
* URL: http://www.mattiasthell.com
*
* */

#include "AudioManager.hpp"

#include <Windows.h>

namespace hny {

	AudioManager* AudioManager::mInstance = 0;

	AudioManager::AudioManager()
	{
	}

	AudioManager::~AudioManager()
	{
		// Destroy all sounds
		AudioMap::iterator i;
		for(i = mAudio.begin(); i != mAudio.end(); i++) {
			Audio* a = i->second;
			delete a;
		}
		mAudio.clear();

		// Destroy main system object
		mFmSystem->release();
	}

	void AudioManager::Destroy() {
		if(mInstance != 0) {
			delete mInstance;
			mInstance = 0;
		}
	}

	AudioManager* AudioManager::GetInstance() {
		if(mInstance == 0)
			mInstance = new AudioManager();
		return mInstance;
	}

	bool AudioManager::Initialize() 
	{
		FMOD_RESULT result;

		// Create main system object
		result = FMOD::System_Create(&mFmSystem);

		if(result != FMOD_OK) {
			MessageBox(0, L"Failed to create FMOD system device!", L"FMOD", 0);
			return false;
		}

		// Initialize FMOD
		result = mFmSystem->init(100, FMOD_INIT_NORMAL, 0);

		if(result != FMOD_OK) {
			MessageBox(0, L"Failed to initialize FMOD!", L"FMOD", 0);
			return false;
		}

		return true;
	}

	void AudioManager::Update()
	{
		mFmSystem->update();
	}

	bool AudioManager::AddAudio(const std::string& file, const std::string& name, bool stream)
	{

		if(mAudio.find(name) != mAudio.end())
			return false;

		Audio* audio = new Audio(mFmSystem);
		bool res = audio->Load(file, stream);

		if(res)
			mAudio.insert(std::make_pair(name, audio));

		return res;
	}

	Audio* AudioManager::GetSound(const std::string& name) {
		
		AudioMap::iterator i = mAudio.find(name);

		return i->second;
	}
}